package com.bsoft.gol.editor.dao;

import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import com.bsoft.gol.editor.editor.ImportLog;
import org.hibernate.Query;
import org.hibernate.StatelessSession;

import java.util.Date;
import java.util.List;

/**
 * Created by yangyi on 2017/5/12.
 */
public abstract class ImportLogDAO extends HibernateSupportDelegateDAO<ImportLog> {

    public ImportLogDAO() {
        this.setKeyField("id");
    }

    /**
     * 查询日志log
     *
     *
     */
    public List<ImportLog> queryDownLoadLogByDataType(final String dataType){
        HibernateStatelessResultAction<List<ImportLog>> action = new AbstractHibernateStatelessResultAction<List<ImportLog>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuffer sbf = new StringBuffer();
                sbf.append("select * from data_import_log where download=0 and fail>0");
                boolean dataTypeSetted = dataType != null && dataType.length() > 0;
                if(dataTypeSetted){
                	sbf.append(" and dataType=?");
                }
                Query query = ss.createSQLQuery(sbf.toString()).addEntity(ImportLog.class);
                if(dataTypeSetted){
                	query.setParameter(0,dataType);
                }
                @SuppressWarnings("unchecked")
                List<ImportLog> list = query.list();
                setResult(list);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return  action.getResult();
    }



    /**
     * 更新记录的下载标记为1和下载时间
     * @param id 表记录ID
     * @param downloadDate 下载时间
     */
    public void updateDownloadInfo(final int id,final Date downloadDate){
        HibernateStatelessResultAction<Void> action = new AbstractHibernateStatelessResultAction<Void>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuffer sbf = new StringBuffer();
                sbf.append(" update data_import_log set download=1,downloadDate=? where id=?");
                Query query = ss.createSQLQuery(sbf.toString());
                query.setParameter(0,downloadDate);
                query.setParameter(1,id);
                query.executeUpdate();
            }
        };
        HibernateSessionTemplate.instance().execute(action);
    }
}
